package com.naiking.core
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Rectangle;

	/**
	 * 逐帧扫描
	 * @author Naiking
	 * 
	 */	
	public class NPerFrameMovieClip extends Sprite
	{
		private var _mc:MovieClip;//原始mc
		private var _bmp:Bitmap;
		private var _bmpdt:BitmapData;
		private var _totalFrames:int;
		private var _cntFrm:int;
		private var _w:int;
		private var _h:int;
		private var _rect:Rectangle;
		private var _cntTimes:int;
		private var _repeat:int;
		public static const EVT_PLAYCOMPLETE:String="EVT_PLAYCOMPLETE";
		public function NPerFrameMovieClip()
		{
			super();
			mouseEnabled=mouseChildren=false;
		}
		public function setMovie(mc:MovieClip,repet:int=1):void
		{
			_mc=mc;
			_repeat=repet;
			_w=mc.loaderInfo.width;
			_h=mc.loaderInfo.height;
			_rect=new Rectangle(0,0,_w,_h)
			_bmpdt=new BitmapData(_w,_h,true,0x00);
			_bmp=new Bitmap(_bmpdt);
			addChild(_bmp);
			_totalFrames=mc.totalFrames;
			addEventListener(Event.ENTER_FRAME,onLoop);
		}
		public function dispose():void
		{
			removeEventListener(Event.ENTER_FRAME,onLoop);
			//_mc.loaderInfo.loader.unloadAndStop();
			_mc.stop();
			_mc=null;
			if(_bmp&&_bmp.bitmapData)
				_bmp.bitmapData.dispose();
		}
		private function onLoop(e:Event):void
		{
			_cntFrm++;
			_mc.gotoAndStop(_cntFrm);
			if(_bmpdt)
				_bmpdt.dispose();
			_bmpdt=new BitmapData(_mc.width,_mc.height,true,0x00);
			_bmpdt.draw(_mc,null,null,null);
			_bmp.bitmapData=_bmpdt;
			if(_cntFrm==_totalFrames)
			{
				_cntFrm=0;
				_cntTimes++;
				if(_cntTimes==_repeat)
				{
					//播放结束了 停止enterfame
					this.removeEventListener(Event.ENTER_FRAME,onLoop);
					dispatchEvent(new Event(EVT_PLAYCOMPLETE));
				}
			}
		}
	}
}